<?php

namespace WeChat\Controller;

use Think\Log;

class PayController extends BaseController {

    function _initialize() {

        parent::_initialize();
    }

    //先去vender下配置  Pay/Wxpay/WxPayPubHelper/Wxpay.pub.config.php
    public function index($id = 0) {

        $order_model = D('Order');
        $ordergoods_model = D('OrderGoods');

        $order_info = $order_model->find($id);

        if (empty($order_info)) {
            $this->error('订单异常', U("WeChat/Index/index"));
        }

        //获取商品订单body信息
        $array_ordergoods_titles = $ordergoods_model->get_ordergoods($order_info['id'], TRUE);

        if (!$array_ordergoods_titles['status']) {

            $this->error($array_ordergoods_titles['msg']);
        }

        $body = $array_ordergoods_titles['msg'];  //提交订单内容(*商品的名称*)

        $openid = get_user_info_wechat($order_info['user_id'], 'openid');  //用户openid

        $notify_url = C('WEB_SITE_DOMAIN') . "/index.php/WeChat/Pay/notify"; //订单支付回调链接

        Log::write('body:' . $body . '; openid:' . $openid . '; notify_url:' . $notify_url);
    //   $order_info['total']=0.01;
        $jsApiParameters = $this->wechat->unifiedOrder($openid, $body, $order_info['order_no'], $order_info['total'], $notify_url);
        Log::write("jsApiParameters:" . $jsApiParameters);

        if ($jsApiParameters) {
            //兼容前端为空出问题的情况
            $this->assign("jsApiParameters", $jsApiParameters);
        } else {
            $this->assign("error", $this->wechat->getError());
        }

        //会员余额
        $array_member_balance = D('Member')->member_balance($order_info['user_id']);

        if (!$array_member_balance['status']) {

            $this->error($array_member_balance['msg'], U('Cart/index'));
        }

        $balance = $array_member_balance['msg'];

        $this->assign("isweixin", $this->isweixin());
        $this->assign('order_info', $order_info);
        $this->assign('balance', $balance);
        $this->display();
    }

    /*
     * 微信支付回调处理函数
     * 
     * @xingji
     */

    public function notify() {
        Log::write('进入微信支付回调处理：');
        //支付成功回调数据
        $data = $this->wechat->getNotify();

        //检测订单的有效性
        if (!array_key_exists("transaction_id", $data)) {
            Log::write('没有检测到订单参数transaction_id');
            return false;
        }

        //查询订单，判断订单真实性     
        if (!$this->Queryorder($data["transaction_id"])) {
            Log::write('订单查询失败');
            return false;
        }

        $result = update_pay_status($data['out_trade_no'], $data);  //修改订单支付状态 

        Log::write('modify order type stutus:' . $result);

   //     $data['out_trade_no'] = '16C059428774657';

        if ($result) {

            //开始进行多级分销
            if (C('IS_OPEN_DISTRIBUTION')) {

                Log::write("支付成功，接下来准备分佣:" . json_encode($data));
         //     $data['out_trade_no'] = '16C059428774657';
                $distrabution = new \Common\Commission\NormalAdapter();

                if (!$distrabution->assign($data['out_trade_no'], C("FX_M_LEVEL"), C("FX_M_RULE"))) {

                    Log::write('分佣失败');
                }
            }

            echo $this->wechat->returnNotify($data);
        }
    }

    /*
     * 查询订单的有效性
     */

    public function Queryorder($transaction_id) {

        $result = $this->wechat->getOrderInfo($transaction_id, 1);

        Log::write("order-query:" . json_encode($result));

        if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {

            return true;
        }

        return false;
    }

    /*
     * 积分支付
     * 
     * @param  type = array('0'=> '积分支付','1'=>'')
     * @
     */

    public function pay_type() {

        $type = I('param.type', 0);

        $order_id = I('order_id');

        if (empty($order_id)) {

            $this->error('参数丢失，请重试！(>﹏<。)～呜呜呜……');
        }

        switch ($type) {
            case 1:

                break;
            default:

                $order_info = D('Order')->get_order_item($order_id, array('total', 'user_id', 'order_no'));

                //会员余额
                $array_balance = D('Member')->member_balance($order_info['user_id']);

                if (!$array_balance['status']) {

                    $this->error($array_balance['msg']);
                }

                $balance = $array_balance['msg'];

                $compare = $balance - $order_info['total'];

                if ($compare < 0) {

                    $this->error('余额不足');
                }

                //处理订单状态
                $data = array(
                    'out_trade_no' => $order_info['order_no'],
                    'openid' => get_user_info_wechat($order_info['user_id'], 'openid'),
                    'fee_type' => 'score',
                    'total_fee' => $order_info['total'] * 100, //方便接下来的订单状态处理
                    'from' => 'xingji-仟米科技'
                );

                update_pay_status($order_id, $data, 1);

                exit;
        }
    }

    /*
     *  模拟微信回调
     *  Author: cys 2016-11-15
     */

    public function localNotify() {

        $out_trade_no = I('post.out_trade_no');

        if ($out_trade_no) {
            //开始进行多级分销
            if (C('IS_OPEN_DISTRIBUTION')) {
                $distrabution = new \Common\Commission\NormalAdapter();
                //Kmeen_system_config  C("FX_M_LEVEL")会员分销层数 3,C("FX_M_RULE")会员分佣规则18|12|8
                if (!$distrabution->assign($out_trade_no, C("FX_M_LEVEL"), C("FX_M_RULE"))) {
                    echo"<meta charset='utf-8'><pre>";
                    print_r('分佣彻底失败');
                    die();
                }
            }
            //返回给微信数据，防止多次回调
            echo"<meta charset='utf-8'><pre>";
            print_r('localNotify分佣方法已走完');
            die();
            $this->success('订单', U("WeChat/index/index"));
            echo $this->wechat->returnNotify($data);
        }
        $this->success('订单', U("WeChat/index/index"));
    }

}
